package com.yswy.common.utils;

import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;


import com.baidu.aip.util.Base64Util;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
@Slf4j
public class ImageBioChangeUtil {

    static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
    static BASE64Decoder decoder = new sun.misc.BASE64Decoder();

    //判断图片是否包含头部信息
    public static StringBuffer imgIshead(StringBuffer urlImageToBase64){
        if(urlImageToBase64.indexOf(",")>-1) {//包含头信息
            urlImageToBase64 = new StringBuffer(urlImageToBase64.substring(urlImageToBase64.indexOf(",")+1));
        }
        return urlImageToBase64;
    }



    //获取图片大小
    public static Boolean getImgSize(String base64 ,String sizeStr ){
        Double size = Double.parseDouble(sizeStr.replace("M",""))*1024;
        Integer base64Size = base64.length()/1024;
        Double fileSize = base64Size*0.7513;
        System.out.println(fileSize);
        if (fileSize <= size){
            return false;
        }else {
            return true;
        }
    }

    /**
     * base64转化成 inputStream
     *
     * @param base64
     * @return
     */
    public static InputStream base64ToInputStream(String base64) {
        ByteArrayInputStream stream = null;
        try {
            byte[] bytes = Base64.getMimeDecoder().decode(base64);
            stream = new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stream;
    }

    /**
     * base64转为图片
     * @param path
     * 文件路径：到文件夹即可，代码里会在文件夹里生成对应的jpg文件
     * @param base64
     * @return
     */
    public static String base64ToJpg(String path,String base64){
        // 判断文件路径是否存在
        File filePath = new File(path);
        if (!filePath.exists()){
            filePath.mkdirs();
        }
        // 创建文件
        String jpgFile = path + "\\" + UUID.randomUUID() + ".jpg";
        File file = new File(jpgFile);
        boolean jpgFileExist = false;
        try {
            jpgFileExist = file.createNewFile();
            log.info("jpg文件创建成功");
        } catch (IOException e) {
            log.info("jpg文件创建失败");
            e.printStackTrace();
        }
        if (jpgFileExist){
            // 解密
            Base64.Decoder decoder = Base64.getDecoder();
            // 去掉base64前缀 data:image/jpeg;base64,
            base64 = base64.substring(base64.indexOf(",", 1) + 1, base64.length());
            byte[] b = decoder.decode(base64);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            // 保存图片
            try {
                FileOutputStream out = new FileOutputStream(jpgFile);
                out.write(b);
                out.flush();
                out.close();
                // 写入成功返回文件路径
                return jpgFile;
            } catch (FileNotFoundException e) {
                log.info("文件未找到");
                e.printStackTrace();
            } catch (IOException e) {
                log.info("写入失败");
                e.printStackTrace();
            }
        }
        return "文件不存在";
    }

    /**
     * 读入文件转换为Base64编码并返回
     * @param filePath 文件路径
     * @return base64 的文件
     * @throws Exception
     */
    public static String readAsBase64FromFile(File filePath) {
        InputStream in = null;
        byte[] data = null;
        try	{
            in = new FileInputStream(filePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Base64Util.encode(data);
    }


    //base64 转 byte
    public static byte[] base64ToImgByteArray(StringBuffer base64){
        byte[] bytes  = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            //因为参数base64来源不一样，需要将附件数据替换清空掉。如果此入参来自canvas.toDataURL("image/png");
            //base64解码并转为二进制数组
            bytes = decoder.decodeBuffer(base64.toString());
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return bytes;
    }



    //从文件路径中获取图片转为二进制
    public static String getImageBinary(String filePath){
        if(StringUtils.isEmpty(filePath)) {
            return null;
        }
        File f = new File(filePath);	//这里gif动态图不可以，虽然在后面也能输出gif格式，但是却不是动图
        BufferedImage bi;
        ByteArrayOutputStream baos = null;
        try {
            bi = ImageIO.read(f);
            baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);
            byte[] bytes = baos.toByteArray();

            return encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 图片URL转Base64编码
     * @param imgUrl 图片URL
     * @return Base64编码
     */
    public static String imageUrlToBase64(String imgUrl) {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;

        try {
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();

            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();

            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用输入流从buffer里把数据读取出来
            while( (len = is.read(buffer)) != -1 ){
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }

            // 对字节数组Base64编码
            return encode(outStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(is != null) {
                    is.close();
                }
                if(outStream != null) {
                    outStream.close();
                }
                if(httpUrl != null) {
                    httpUrl.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    /**
     * 图片转字符串
     * @param image 图片Buffer
     * @return Base64编码
     */
    public static String encode(byte[] image){
        BASE64Encoder decoder = new BASE64Encoder();
        return replaceEnter(decoder.encode(image));
    }

    /**
     * 字符替换
     * @param str 字符串
     * @return 替换后的字符串
     */
    public static String replaceEnter(String str){
        String reg ="[\n-\r]";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }

    //从URl中获取图片转为二进制
    public static String getImageBinaryFromUrl(String urlPath) throws Exception{
        if(StringUtils.isEmpty(urlPath)) {
            return "";
        }
        URL url=new URL(urlPath);
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(3000);//超时提示1秒=1000毫秒
        InputStream inStream=conn.getInputStream();//获取输出流
        byte[] data=readInputStream(inStream);
        return encoder.encodeBuffer(data).trim();

    }
    //readInputStream方法
    private static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024];//转换为二进制
        int len=0;
        while((len =inStream.read(buffer))!=-1){
            outStream.write(buffer,0,len);
        }
        return  outStream.toByteArray();
    }
    //将二进制转为图片
    public static void base64StringToImage(String base64String,String outFilePath){
        if(StringUtils.isNotEmpty(base64String)&&StringUtils.isNotEmpty(outFilePath)) {
            try {
                byte[] bytes1 = decoder.decodeBuffer(base64String);

                ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
                BufferedImage bi1 =ImageIO.read(bais);
                File w2 = new File(outFilePath);//可以是jpg,png格式
                if (!w2.exists()) {   //文件不存在则创建文件，先创建目录
                    File dir = new File(w2.getParent());
                    dir.mkdirs();
                    w2.createNewFile(); // 创建新文件
                }
                ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片，此处不需改动
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 通过网络地址获取文件InputStream（持续获取）
     *
     * @param path 地址
     * @return
     */
    public static InputStream returnBitMap(String path) {
        if (StringUtils.isBlank(path)) {
            return null;
        }
        URL url = null;
        InputStream is = null;
        byte[] data = null;
        try {
            url = new URL(path);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            // 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            // 得到网络返回的输入流
            is = conn.getInputStream();
            // 重要：readStream
            data = readStream(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        InputStream inputStream = new ByteArrayInputStream(data);
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
    }


    public static void main(String[] args) {

        String outFilePath= "C:\\Users\\mxy\\Desktop\\apks\\1234.jpg";
        String s = readAsBase64FromFile(new File(outFilePath));
        Boolean imageBinary = getImgSize(s , "4M");

        System.out.println(imageBinary);
    }
}
